package com.future.servlet;

import com.future.biz.LoginBIZ;
import com.future.model.bo.RegisterBO;
import com.future.model.bo.UserBO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class RegistServlet extends LoginServlet {
	private static Logger logger = LogManager.getLogger("RegistServlet");

	public RegistServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	}

	public void doGet(HttpServletRequest request,
										HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		logger.debug("this is doGet");
	}

	public void doPost(	HttpServletRequest request,
											HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();

		String registName = request.getParameter("regist-username");
		String registEmail = request.getParameter("regist-email");
		String registPassword = request.getParameter("regist-password");
		String registPasswordConfirm = request.getParameter("regist-password-confirm");
		String registPhone = request.getParameter("regist-phone");
		String registRealname = request.getParameter("regist-realname");
		String registUnit = request.getParameter("regist-unit");
		String registTel = request.getParameter("regist-tel");

		RegisterBO registerBo = new RegisterBO();
		registerBo.setEmail(registEmail);
		registerBo.setUsername(registName);
		registerBo.setPassword(registPassword);
		registerBo.setPasswordConfirm(registPasswordConfirm);
		registerBo.setPhone(registPhone);
		registerBo.setRealName(registRealname);
		registerBo.setUnit(registUnit);
		registerBo.setRegisterTel(registTel);
		registerBo.setAreaId(registName.substring(0, registName.length() - 2));
		registerBo.setDepartmentId(Integer.valueOf(registName.substring(registName.length() - 2)));
		LoginBIZ loginBiz = new LoginBIZ();
		logger.debug(registerBo);
		try {
			UserBO bo = loginBiz.regist(registerBo);
			if (bo == null)
				throw new Exception();
			loginForward(request, response, bo);
		} catch (Exception e) {
			out.print(e);
			out.flush();
			out.close();
			logger.error(e);
		}
	}

	public void init() throws ServletException {
		// Put your code here
	}

}
